package com.yenlien.traceyun.milk.service;

import com.yenlien.traceyun.business.dao.ProcessDetailDao;
import com.yenlien.traceyun.business.entity.ProcessDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProcessDetailService {
    @Autowired
    private ProcessDetailDao processDetailDao;

    public Page<ProcessDetail> findByList(final ProcessDetail processDetail) {
        Pageable pageable = PageRequest.of(processDetail.getPage(), processDetail.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return processDetailDao.findAll(new Specification<ProcessDetail>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<ProcessDetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> productName = root.get("productName");

                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNotEmpty(processDetail.getCompanyId())) {
                    list.add(cb.equal(root.get("companyId"), processDetail.getCompanyId()));
                }
                if (StringUtils.isNotEmpty(processDetail.getProductName())) {
                    list.add(cb.like(productName, "%" + processDetail.getProductName() + "%"));
                }
                Predicate[] predicate = new Predicate[list.size()];
                Predicate pre_and = cb.and(list.toArray(predicate));
                return pre_and;
            }
        }, pageable);
    }

    public void bindProduct(String id, String productId) {
        ProcessDetail processDetail = processDetailDao.findById(id);
        processDetail.setProductId(productId);
        processDetailDao.save(processDetail);
    }

    public ProcessDetail findById(String id) {
        return processDetailDao.findById(id);
    }
}
